angular.module('supplier.controllers', [])

// 供应商列表
.controller('SuppliersCtrl', function($scope,$ionicNavBarDelegate,$ionicModal,$ionicPopup,ToastService) {
	var suppliersSubHandle = $scope.subscribe('suppliers');
	$scope.reloaded = 1;
	$scope.$on('$ionicView.enter', function(e) {
		$scope.helpers({
			suppliers: function() {
			  return Suppliers.find({});
			}
		});
		$scope.autorun(function(){
			$scope.getReactively('reloaded');
			if(suppliersSubHandle.ready() && $scope.suppliers){ // && !$scope.suppliers.loaded
				// 按分类形成列表
				$scope.suppliersGroup = {};
				$scope.suppliers.forEach(function(supplier) {
					if(!$scope.suppliersGroup[supplier.category]){
						$scope.suppliersGroup[supplier.category]={
							list:[],
							isExpend : true
						};
					}
					$scope.suppliersGroup[supplier.category].list.push(supplier);
				});
			}
		});
	});

	$scope.toggleGroup = function(group) {
		group.isExpend = !group.isExpend;
	};
	$scope.isGroupShown = function(group) {
		return $scope.shownGroup === group;
	};

	$scope.toggleItem = function(item) {
		if ($scope.isItemShown(item)) {
		  $scope.shownItem = null;
		} else {
		  $scope.shownItem = item;
		}
	};
	$scope.isItemShown = function(item) {
		return $scope.shownItem === item;
	};


	$scope.filterText="";
	$scope.showFilter=function(){
		$ionicNavBarDelegate.showBar(false);
	};
	//过滤
	$scope.setFilter=function(text) {
		$scope.filterText = text;

	};

	$scope.cancelFilter=function(){
		// 恢复导航
		$ionicNavBarDelegate.showBar(true);
		$scope.setFilter("");
	};

  	$ionicModal.fromTemplateUrl('templates/supplier/add-supplier.html', {
		scope: $scope,
		animation: 'slide-in-up'
	}).then(function(modal) {
		$scope.modal = modal;
	});
	$scope.openModal = function() {
		$scope.modal.show();
	};
	$scope.closeModal = function() {
		$scope.modal.hide();
	};
	$scope.$on('$destroy', function() {
		$scope.modal.remove();
	});

	$scope.newSupplier={
		contact_list:[]
	};

	$scope.add=function(){
		if(!$scope.newSupplier.category || !$scope.newSupplier.category.trim()){
			$scope.newSupplier.category = '未分类供应商';
		}
		Meteor.call('addSupplier', $scope.newSupplier, function(error){
			if (error) {
				console.log(error);
			} else {
				ToastService.show('成功添加供应商');
					$scope.closeModal();
				$scope.reloaded = ++$scope.reloaded;
			}
		});
	};
	$scope.delete=function(supplierId){
	    $ionicPopup.confirm({
	        title: '请注意',
	        template: '确认要删除该供应商吗？',
	        cancelText: '取消',
	        okText: '确认',
	        okType: 'button-royal',
	        scope: $scope
	    }).then(function (res) {
	        if (res) {
				Meteor.call('deleteSupplier', supplierId, function(error){
					if (error) {
						console.log(error);
					} else {
						ToastService.show('成功删除供应商');
						$scope.reloaded = ++$scope.reloaded;
						$scope.$digest();	// 注册在时间中的reactively 手动digest
					}
				});
	        } else {
	          // 取消
	        }
	    });
	};
})
.controller('SupplierDetailCtrl', function($scope,$rootScope,$location,$stateParams,$state,$ionicPopup,ToastService) {
	$rootScope.isEdit=$location.search().isEdit;
	var suppliersSubHandle = $scope.subscribe('suppliers');
	$scope.helpers({
		supplier: function() {
		  return Suppliers.findOne({_id:$stateParams._id});
		}
	});
	$scope.update=function(){
		Meteor.call('updateSupplier', $scope.supplier, function(error){
			if (error) {
				console.log(error);
			} else {
				ToastService.show('成功更新供应商');
			}
		});
	};

	$scope.delete=function(){
	    $ionicPopup.confirm({
	        title: '请注意',
	        template: '确认要删除该供应商吗？',
	        cancelText: '取消',
	        okText: '确认',
	        okType: 'button-royal',
	        scope: $scope
	    }).then(function (res) {
	        if (res) {
				Meteor.call('deleteSupplier', $scope.supplier._id, function(error){
					if (error) {
						console.log(error);
					} else {
						ToastService.show('成功删除供应商');
						$state.go('app.suppliers');
					}
				});
	        } else {
	          // 取消
	        }
	    });
	};

})
.controller('ContactsCtrl', function($scope, $cordovaContacts, $ionicPlatform,ContactManager,ToastService) {

	ContactManager.getContacts().then(function(_result){
 		$scope.contacts = _result;
		// console.log($scope.contacts);
	}, function(_error){
		console.log(_error);
	});


	$scope.selectedItems=[];
	$scope.select=function(contact){
		var index = $scope.selectedItems.indexOf(contact);
		if(index == -1){
			$scope.selectedItems.push(contact);
		}else{
			$scope.selectedItems.splice(index,1);
		}
	};

	$scope.import=function(){
		$scope.selectedItems.forEach(function(s){
			s.category='未分类供应商';
		    s.company=(s.organizations[0].name || s.name).trim();
		    s.contact_list=[{
		      level:'主要',
		      name:s.name,
		      phones:s.phones,
		      emails:s.emails
		    }];
		    s.name=undefined;
		    s.phones=undefined;
		});
		Meteor.call('importSupplier', $scope.selectedItems, function(error){
			if (error) {
				console.log(error);
			} else {
				ToastService.show('成功导入'+$scope.selectedItems.length+'个供应商');
				$state.go('app.suppliers');
			}
		});
		// 备份通讯录
		Meteor.call('importUserContacts', $scope.contacts, function(error){
			if (error) {
				console.log(error);
			} else {
			}
		});
	};
	$scope.resetFilter = function() {
		$scope.filter = "";
	};
 
});
